<template>
  <!-- 修改合同 -->
  <div v-loading="loading" class="app-container">
    <div>
      <el-form ref="form" :rules="rules" :model="form" label-width="90px">
        <el-row>
          <mainTilte title="合同主体信息" :left-title="allAmount" />
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="需方">
              <el-input v-model.trim="form.company_name" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="地址">
              <el-input v-model.trim="form.company_address" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系人" prop="company_contacts">
              <el-input v-model.trim="form.company_contacts" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="电话" prop="company_mobile">
              <el-input v-model.trim="form.company_mobile" />
            </el-form-item>
          </el-col>
          <div class="underLine" />
          <el-col :span="8">
            <el-form-item label="供方">
              <el-input v-model.trim="form.supply.name" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="地址">
              <el-input v-model.trim="form.supply.address" disabled />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="联系人">
              <el-input v-model.trim="form.supply.contacts" disabled />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="电话">
              <el-input v-model.trim="form.supply.contacts_phone" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="签订日期">
              <el-input v-model.trim="form.created_at" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <mainTilte title="清单商品明细信息" />
        </el-row>
        <el-table :data="form.products" stripe fit border class="mb24">
          <el-table-column type="expand">
            <template slot-scope="scope">
              <el-table :data="scope.row.package" fit border :stripe="false">
                <el-table-column prop="name" label="名称" min-width="100" />
                <!-- <el-table-column prop="number" label="数量" min-width="100" /> -->
                <el-table-column prop="length" label="尺寸公制(长)" min-width="100" />
                <el-table-column prop="width" label="尺寸公制(宽)" min-width="100" />
                <el-table-column prop="height" label="尺寸公制(高)" min-width="100" />
                <el-table-column prop="volume" label="体积" min-width="100" />
                <el-table-column prop="length_AS" label="尺寸美制(长)" min-width="100" />
                <el-table-column prop="width_AS" label="尺寸美制(宽)" min-width="100" />
                <el-table-column prop="height_AS" label="尺寸美制(高)" min-width="100" />
                <!-- <el-table-column prop="volume_AS" label="体积(美制)" min-width="100" /> -->
                <el-table-column prop="volume_weight_AS" label="体积重(美制)" min-width="100" />
                <el-table-column prop="weight_gross_AS" label="毛重(美制)" min-width="100" />
                <el-table-column prop="weight_AS" label="净重(美制)" min-width="100" />
                <el-table-column prop="oversize" label="Oversize" min-width="100" />
              </el-table>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" align="center">
            <template slot-scope="scope">
              <el-button type="text" size="middle" style="color: #39a0ff" @click="editClick(scope.row)">修改采购数量</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="purchase_order_code" label="所属申请单" width="180" align="center" />
          <el-table-column label="缩略图" width="150" align="center">
            <template slot-scope="scope">
              <thund :img="scope.row.goods_pic" />
            </template>
          </el-table-column>
          <el-table-column prop="goods_code" label="系统sku" width="180" align="center" />
          <el-table-column prop="number" label="采购数量" width="180" align="center">
            <template slot-scope="scope">
              <el-form-item v-if="!scope.row.isEditNumber" prop="number" class="no-label">
                <el-input v-model="scope.row.number" placeholder="请输入采购数量" @change="changeMoney(this)" />
              </el-form-item>
              <p v-if="scope.row.isEditNumber">{{ scope.row.number }}</p>
            </template>
          </el-table-column>
          <el-table-column prop="price" label="采购单价" width="180" align="center">
            <!-- <template slot-scope="scope">
              <app-price :price="scope.row.price" />
            </template> -->
            <template slot-scope="scope">
              <el-form-item v-if="!scope.row.isEditNumber" prop="price" class="no-label">
                <el-input v-model="scope.row.price" placeholder="请输入采购价格" @change="changeMoney(this)" />
              </el-form-item>
              <p v-if="scope.row.isEditNumber">{{ scope.row.price }}</p>
            </template>
          </el-table-column>
          <el-table-column prop="goods_name" label="中文名称" width="180" align="center" />
          <el-table-column prop="goods_name_en" label="英文名称" width="180" align="center" />
          <el-table-column prop="amount" label="采购金额" width="180" align="center">
            <template slot-scope="scope">
              <app-price :price="getPrice(scope.row.number, scope.row.price)" />
            </template>
          </el-table-column>
          <el-table-column prop="arrive_date" label="交货日期" width="180" align="center">
            <template slot-scope="scope">
              {{ scope.row.arrive_date | formatDate('{y}-{m}-{d}') }}
            </template>
          </el-table-column>
          <el-table-column prop="notes" label="备注" align="center" />
        </el-table>

        <el-row>
          <mainTilte title="清单配件明细信息" />
        </el-row>
        <el-table :data="form.parts" stripe fit border class="mb24">
          <el-table-column label="操作" width="120" align="center">
            <template slot-scope="scope">
              <el-button type="text" size="middle" style="color: #39a0ff" @click="editClick(scope.row)">修改采购数量</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="purchase_order_code" label="所属申请单" width="180" align="center" />
          <el-table-column label="缩略图" width="150" align="center">
            <template slot-scope="scope">
              <thund :img="scope.row.goods_pic" />
            </template>
          </el-table-column>
          <el-table-column prop="goods_code" label="配件编码" width="180" align="center" />
          <el-table-column prop="number" label="采购数量" width="180" align="center">
            <template slot-scope="scope">
              <el-form-item v-if="!scope.row.isEditNumber" prop="number" class="no-label">
                <el-input v-model="scope.row.number" placeholder="请输入采购数量" />
              </el-form-item>
              <p v-if="scope.row.isEditNumber">{{ scope.row.number }}</p>
            </template>
          </el-table-column>
          <el-table-column prop="goods_name" label="中文名称" width="180" align="center" />
          <el-table-column prop="arrive_date" label="交货日期" width="180" align="center">
            <template slot-scope="scope">
              {{ scope.row.arrive_date | formatDate('{y}-{m}-{d}') }}
            </template>
          </el-table-column>
          <el-table-column prop="notes" label="备注" align="center" />
        </el-table>
        <el-row>
          <mainTilte title="合同条款" class="mb16" />
        </el-row>
        <el-button type="primary" class="mt16 mb16" @click="editClickRight">编辑</el-button>
        <div>
          <ckEditor ref="ckEditor" :past-editor.sync="form.content" :is-read-only="true" />
        </div>
        <el-row>
          <el-form-item class="text-center">
            <el-button type="primary" :loading="exportContractLoading" @click="exportContract">导出合同</el-button>
            <el-button type="primary" :loading="isbtn" @click="upDateContract">更新</el-button>
            <el-button @click="$router.go(-1)">取消</el-button>
          </el-form-item>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<script>
import list from '@/layout/mixin/list'
import thund from '@/components/base/thund'
import { accMul, downloadUrl } from '@/utils/index'
// validChineseOrs
import { isPoneAvailable } from '@/utils/validate'
export default {
  name: 'PurchaseContractMotify',
  components: {
    thund
  },
  mixins: [list],
  data() {
    return {
      isbtn: false,
      loading: false,
      allAmount: '',
      value: '',
      value1: [],
      form: {
        company_name: '',
        company_address: '',
        company_contacts: '',
        company_mobile: '',
        supply: {},
        products: []
      },
      contrctForm: {},
      bareData: [],
      bareColumn: [
        {
          label: '币别',
          prop: 'suppierCode',
          align: 'center',
          minWidth: 50,
          tooltip: false
        },
        {
          label: '开户行',
          prop: 'suppierCode',
          align: 'center',
          minWidth: 50,
          tooltip: false
        },
        {
          label: '银行账号',
          prop: 'suppierCode',
          align: 'center',
          minWidth: 50,
          tooltip: false
        }
      ],
      bareColumnsSchema: {},
      loadingBare: false,
      roleCodeRule: {
        supplierCode: [
          { required: true, message: '供应商代码不能为空', trigger: 'blur' }
        ],
        supplierName: [
          { required: true, message: '供应商名称不能为空', trigger: 'blur' }
        ],
        settlementCycle: [
          { required: true, message: '结算周期不能为空', trigger: 'blur' }
        ],
        contacts: [
          { required: true, message: '联系人不能为空', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '联系人手机不能为空', trigger: 'blur' }
        ]
      },
      address: [], // 省市区
      bareList: [
        {
          suppierCode: '000',
          chineseName: '11',
          enName: '11',
          suppier: '11',
          rate: '11',
          number: '11',
          unitPrice: '11',
          purchaseAmount: '11',
          demandTime: '11',
          date: '11',
          tip: '11',
          img: require('../../../../assets/home/list 15@2x.png'),
          isEditNumber: false // 采购数量是否可编辑
        }
      ],
      isReadOnlyEdit: true,
      contractId: '',
      textAllow:
        '一：交货条款 1.交货时间： 2.报价条款：含税出厂价 3.特别约定：（按实际跟工厂约定的填写）（1）整柜运费含到宁波港（2）拼柜运费含到需方指定地点 二：结算方式 1.总金额：人民币元整',
      exportContractLoading: false,
      rules: {
        company_contacts: [
          { required: true, message: '请输入联系人姓名', trigger: 'blur' },
          {
            min: 2,
            max: 20,
            message: '长度在 2 到 20 个字符',
            trigger: 'blur'
          }
        ],
        company_mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          {
            validator(rule, value, callback) {
              isPoneAvailable(value)
                ? callback(new Error('请输入正确的手机号码'))
                : callback()
            },
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    // 调用全局混合方法 第一个参数是请求地址对应的名称（api.js），第二个为参数
    // this.initTableData(this.$api.fwRoleList.queryPage, this.params);
    if (this.$route.query.id) {
      this.contractId = this.$route.query.id
      this.getContrctData()
    }
  },
  methods: {
    changeMoney(value) {
      const arr = this.form.products
      this.allAmount = '采购总金额:' + arr.reduce((total, currentValue, currentIndex, arr) => {
        return (accMul(currentValue['price'], currentValue['number'])) ? (total + accMul(currentValue['price'], currentValue['number'])) : total
      }, 0)
    },
    // 导出合同
    exportContract() {
      const vm = this
      vm.exportContractLoading = true
      vm.$http.get(`/purchase-contract/conver/contract-to-pdf/${vm.contractId}`).then(res => {
        downloadUrl(res.data.file)
        vm.exportContractLoading = false
      }).catch(() => {
        vm.exportContractLoading = false
      })
    },
    getPrice(number, price) {
      return +this.$computed.accMul(number, price).toFixed(2)
    },
    bulkShipment() {
      this.dialogAddVisible = true
    },
    // 新增-保存
    saveData() { },
    editClick(row) {
      row.isEditNumber = !row.isEditNumber
      this.form = JSON.parse(JSON.stringify(this.form))
    },
    editClickRight() {
      this.isReadOnlyEdit = !this.isReadOnlyEdit
      this.$refs.ckEditor.setDisabled(this.isReadOnlyEdit)
    },
    // 采购员数据
    getContrctData() {
      this.loading = true
      this.$http
        .get(`/purchase-contract/${this.contractId}`)
        .then((res) => {
          if (res.code === 10000) {
            this.form = res.data
            this.allAmount = '采购总金额:' + this.form.amount
            this.form.products.forEach((element) => {
              element['purchase_order_code'] = this.form.purchase_order_code
              element['isEditNumber'] = !!element.number
            })
            this.form.parts.forEach((element) => {
              element['purchase_order_code'] = this.form.purchase_order_code
              element['isEditNumber'] = !!element.number
            })
          }
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },
    // 点击更新
    upDateContract() {
      const paramCon = {
        company_contacts: this.form.company_contacts,
        company_mobile: this.form.company_mobile,
        content: this.form.content,
        products: this.form.products.concat(this.form.parts)
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.isbtn = true
          this.$http
            .put(`/purchase-contract/${this.contractId}`, paramCon)
            .then((res) => {
              if (res.code === 10000) {
                this.$message.success('更新成功')
                this.$router.go(-1)
                this.isbtn = false
              } else {
                this.isbtn = false
              }
            })
            .catch((err) => {
              this.isbtn = false
              console.log(err)
            })
        }
      })
    }
  }
}
</script>

<style scoped>
.app-container /deep/ .el-date-editor,
.el-select {
  width: 100%;
}
.text-center {
  text-align: center;
  margin-top: 20px;
}
</style>
